//
//  MainViewController.m
//  EmojiTextViewDemo
//
//  Created by lixy on 15/3/4.
//  Copyright (c) 2015年 lixy. All rights reserved.
//
#define FONT_SIZE 14.0f
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f


#import "MainViewController.h"
#import "BaseInputBar.h"
#import "UIKit+BaseExtension.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
#import "ChartMessage.h"
#import "ChatTableViewCell.h"
#import "MLEmojiLabel.h"
#import "ChartMessage.h"
@interface MainViewController ()<UITextViewDelegate, UITableViewDelegate, UITableViewDataSource, BaseInputBarDelegate,AVAudioPlayerDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    NSString *filePath;
    NSString *fullImgPath;
    
    UITableViewCell *_cell;
    NSString * content;
    ChatTableViewCell * _chatCell;
    NSMutableArray * photoArr;
}
@property (nonatomic, strong) BaseInputBar *inputBar;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic) CGRect keyboardRect;//键盘rect

@property (nonatomic,strong) NSMutableArray *cellFrames;
@property (nonatomic,assign) BOOL recording;
@property (nonatomic,strong) NSString *fileName;
@property(nonatomic,strong)  NSString * imgFileName;
@property (nonatomic,strong) AVAudioRecorder *recorder;
@property (nonatomic,strong) AVAudioPlayer *player;

@property(nonatomic,strong)NSString * flag;
@end
static NSString *const cellIdentifier=@"QQChart";

@implementation MainViewController
static int a=2;
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=@"聊天";
    self.cellFrames=[[NSMutableArray alloc]init];
    _cell=[[UITableViewCell alloc]init];
    _chatCell=[[ChatTableViewCell alloc]init];
    photoArr=[[NSMutableArray alloc]init];
    
    content=[[NSString alloc]init];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    _inputBar = [[BaseInputBar alloc] init];
    _inputBar.delegage = self;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainScreenWidth, MainScreenHeight-NavBarHeight-StatusBarHeight-_inputBar.height)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeInteractive;
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];
    
    _inputBar.top = self.tableView.bottom;
    
    [self.view addSubview:_inputBar];
    Reachability * reach=[Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus status=[reach currentReachabilityStatus];
    if(status==NotReachable)//如果没有网络
    {
        NSLog(@"没有网络!");
        self.flag=@"1";
    }
    else//有网络
    {
        //初始化数据
        [self initwithData];
    }

}
-(void)removeAllFile
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSFileManager * fl=[[NSFileManager alloc]init];
    NSLog(@"%@",[fl subpathsAtPath:documentsDirectory]);

    //清除附件
    BOOL result = [[NSFileManager defaultManager] removeItemAtPath:documentsDirectory error:nil];
    if (result) {
        NSLog(@"ok");
    }

}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //如果不是手势引起的滚动就不执行跟随键盘
    if (scrollView.panGestureRecognizer.numberOfTouches == 0) {
        return;
    }
    
    CGPoint point = [scrollView.panGestureRecognizer locationInView:nil];
    
    if (point.y > MainScreenHeight-_inputBar.height || point.y < MainScreenHeight-self.keyboardRect.size.height) {
        return;
    }
    
    point.y = point.y - NavBarHeight - StatusBarHeight;
    
    _inputBar.top = point.y;
    self.tableView.height = point.y;
    
}
#pragma  mark   点击相册中的图片 货照相机照完后点击use  后触发的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
  
    /*  此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
  */
    self.imgFileName=[NSString stringWithFormat:@"icon0%d.jpg",a];
    // 保存图片至本地，方法见下文
    [self saveImage:image withName:self.imgFileName];
}
#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    fullImgPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    [imageData writeToFile:fullImgPath atomically:NO];
    a++;
    [self sendMessageWithMsg:self.imgFileName];
}


#pragma mark  点击cancel 调用的方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = [self.cellFrames objectAtIndex:[indexPath row]];
    CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
    NSDictionary * attributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:FONT_SIZE] forKey:NSFontAttributeName];
    NSAttributedString *attributedText =
    [[NSAttributedString alloc]
     initWithString:text
     attributes:attributes];
    CGRect rect = [attributedText boundingRectWithSize:constraint
                                               options:NSStringDrawingUsesLineFragmentOrigin
                                               context:nil];
    CGSize size = rect.size;
    CGFloat height = MAX(size.height, 64.0f);
    return height +20.0f+ (CELL_CONTENT_MARGIN * 2);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //return self.dataSource.count;
    return self.cellFrames.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        NSString * text=[self.cellFrames objectAtIndex:indexPath.row];
        MLEmojiLabel * label;
        UIImageView * ivm=[[UIImageView alloc]init];
        static NSString *cellName = @"cellname";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
            UIImageView * iv=[[UIImageView alloc]init];
            iv.frame=CGRectMake(20, 15, 50, 50);
            iv.image=[UIImage imageNamed:@"saga.png"];
            iv.backgroundColor=[UIColor redColor];
            [cell.contentView addSubview:iv];
            
            NSString *str = @"icon0";
            NSString *temp=[self.cellFrames objectAtIndex:indexPath.row];
            NSRange foundObj=[temp rangeOfString:str];
            if(foundObj.length>0) {
                NSLog(@"Yes ! str found,  %@",temp);
                ivm.frame=CGRectMake(90, 15, 70, 70);
                [ivm setTag:1000];
                NSLog(@"imgname=%@",fullImgPath);
                //图片不在沙盒路径里
                if (!fullImgPath) {
                    ivm.image=[UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",temp]];
                    [cell.contentView addSubview:ivm];
                    _cell=cell;
                    return cell;
                }
                
                fullImgPath=[NSString documentPathWith:temp];
                //从路径加载图片
                ivm.image=[UIImage imageWithContentsOfFile:fullImgPath];
                [cell.contentView addSubview:ivm];
                _cell=cell;
                return cell;
            }
            ivm.hidden=YES;
            label = [[MLEmojiLabel alloc] init];
            label.customEmojiRegex = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
            label.customEmojiPlistName=@"faceDicMap_ch.plist";
            label.frame=CGRectMake(80, 15, 130, 80);
            [label setLineBreakMode:NSLineBreakByWordWrapping];
            label.backgroundColor=[UIColor lightGrayColor];
            [label setMinimumScaleFactor:FONT_SIZE];
            [label setNumberOfLines:0];
            [label sizeToFit];
            [label setFont:[UIFont systemFontOfSize:FONT_SIZE]];
            [label setTag:1];
            //[[label layer] setBorderWidth:0.5f];
            [[cell contentView] addSubview:label];
        }
        
        
        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        
        NSAttributedString *attributedText = [[NSAttributedString alloc]initWithString:text attributes:@{
                                                                                                         NSFontAttributeName:[UIFont systemFontOfSize:FONT_SIZE]
                                                                                                         }];
        CGRect rect = [attributedText boundingRectWithSize:constraint
                                                   options:NSStringDrawingUsesLineFragmentOrigin
                                                   context:nil];
        CGSize size = rect.size;
        
        if (!label)
            label = (MLEmojiLabel *)[cell viewWithTag:1];
        
        [label setEmojiText:text];
        [label setFrame:CGRectMake(90, 15,170, MAX(size.height, 44.0f))];
        _cell=cell;
        return cell;
    
}
#pragma mark 刷新数据
-(void)initwithData
{
    NSString * tes=@"年后我们打算去北京旅游观光你好哦根据报名情况汇总";
    [self.cellFrames addObject:tes];
    [self.cellFrames addObject:@"nihao"];
    [self.cellFrames addObject:@"hello"];
    [self.cellFrames addObject:@"icon01"];
    [self.cellFrames addObject:@"hello"];
    [self.cellFrames addObject:@"hello world"];
    [self.tableView reloadData];
}

#pragma mark 开始录音
-(void)beginRecord
{
    NSLog(@"begin record");
    if(self.recording)return;
    
    self.recording=YES;
    
    NSDictionary *settings=[NSDictionary dictionaryWithObjectsAndKeys:
                            [NSNumber numberWithFloat:8000],AVSampleRateKey,
                            [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                            [NSNumber numberWithInt:1],AVNumberOfChannelsKey,
                            [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                            [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                            [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                            nil];
    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayAndRecord error: nil];
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    NSDate *now = [NSDate date];
    NSDateFormatter *dateFormater = [[NSDateFormatter alloc] init];
    [dateFormater setDateFormat:@"yyyyMMddHHmmss"];
    NSString *fileName = [NSString stringWithFormat:@"rec_%@.wav",[dateFormater stringFromDate:now]];
    self.fileName=fileName;
    
    filePath=[NSString documentPathWith:fileName];
    NSLog(@"lujing %@",filePath);
    NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
    NSError *error;
    self.recorder=[[AVAudioRecorder alloc]initWithURL:fileUrl settings:settings error:&error];
    [self.recorder prepareToRecord];
    [self.recorder setMeteringEnabled:YES];
    [self.recorder peakPowerForChannel:0];
    [self.recorder record];

}

-(void)finishRecord
{
    NSLog(@"finish record");
    self.recording=NO;
    [self.recorder stop];
    self.recorder=nil;
    [self sendMessageWithMsg:self.fileName];
   

}
-(void)initPlayer{
    //初始化播放器的时候如下设置
    //    UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback;
    //    AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
    //                            sizeof(sessionCategory),
    //                            &sessionCategory);
    //
    //    UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
    //    AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,
    //                             sizeof (audioRouteOverride),
    //                             &audioRouteOverride);
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //默认情况下扬声器播放
    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    [audioSession setActive:YES error:nil];
    audioSession = nil;
}
#pragma mark 发送照片的方法
-(void)sendPhoto:(NSString *)type
{
    if ([type isEqualToString:@"120"]) {//相册
        NSLog(@"120");
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            //pickerImage.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
            
        }
        pickerImage.delegate = self;
        pickerImage.allowsEditing = YES;
        [self presentViewController:pickerImage animated:YES completion:nil];
    
    }else if([type isEqualToString:@"130"]){//照相机
        NSLog(@"130");
        //先设定sourceType为相机，然后判断相机是否可用（ipod）没相机，不可用将sourceType设定为相片库
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        //    if (![UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) {
        //        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //    }
        //sourceType = UIImagePickerControllerSourceTypeCamera; //照相机
        //sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //图片库
        //sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum; //保存的相片
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;
        picker.allowsEditing = YES;//设置可编辑
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
    
    }
    
    
    
    
}
#pragma mark 发送表情和文字消息 一个表情占有4个字符 baseinputBar的代理方法
- (void)sendMessageWithMsg:(NSString *)msg
{
    content=msg;
    NSLog(@"jie mian fasong %lu",(unsigned long)msg.length);
    MLEmojiLabel * labelMsg=(MLEmojiLabel *)[_cell.contentView viewWithTag:1];
    labelMsg.customEmojiRegex = @"\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]";
    labelMsg.customEmojiPlistName=@"faceDicMap_ch.plist";
    [labelMsg setEmojiText:msg];
    [self.cellFrames addObject:msg];
    [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:self.cellFrames.count-1 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView reloadData];
    if (self.cellFrames.count>0) {
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.cellFrames.count-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    _inputBar.inputView.num=0;
    
}

- (void)keyboardWillShow:(NSNotification *)notification
{
    _keyboardRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    NSLog(@"%@", [NSValue valueWithCGRect:_keyboardRect]);
    
    self.tableView.height = MainScreenHeight-NavBarHeight-StatusBarHeight-self.keyboardRect.size.height;
    _inputBar.top = MainScreenHeight-NavBarHeight-StatusBarHeight-self.keyboardRect.size.height;
    
    if (self.dataSource.count) {
        NSIndexPath *indexPath = [[self.tableView indexPathsForVisibleRows] lastObject];
        [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    _keyboardRect = CGRectZero;
    
    self.tableView.height = MainScreenHeight-NavBarHeight-StatusBarHeight-_inputBar.height-self.keyboardRect.size.height;
    _inputBar.top = self.tableView.bottom;
    
}

- (void)addKeyboardNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)removeKeyboardNotification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addKeyboardNotification];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self removeKeyboardNotification];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
    [[UIDevice currentDevice]setProximityMonitoringEnabled:NO];
    [self.player stop];
    self.player=nil;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = @"rec_";
    NSString *temp=[self.cellFrames objectAtIndex:indexPath.row];
    NSRange foundObj=[temp rangeOfString:str];
    
    if(foundObj.length>0) {
        NSLog(@"Yes ! str found");
        filePath=[NSString documentPathWith:temp];
        //播放声音文件
        NSURL *fileUrl=[NSURL fileURLWithPath:filePath];
        [self initPlayer];
        NSError *error;
        self.player=[[AVAudioPlayer alloc]initWithContentsOfURL:fileUrl error:&error];
        [self.player setVolume:1];
        [self.player prepareToPlay];
        [self.player setDelegate:self];
        [self.player play];
        [[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
    }
    else {
        NSLog(@"Oops ! no str");
    }
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}
@end
